// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: "jiwu-5glbnwui4460186f"
}) // 使用当前云环境
const MAX_LIMIT = 100
const db = cloud.database()
const _ = db.command



// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log("event",event)
  let count = await cloud.database().collection("favRecord").where({
    account: event.account,
    selectLib: event.selectLib
  }).count()
  let total = count.total
  //计算需分几次取
  let batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  let tasks = []
  for (let i = 0; i < batchTimes; i++) {
    let promise = db.collection("favRecord").where({
      account: event.account,
      selectLib: event.selectLib
    }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  let res = {
    data: []
  }
  console.log(tasks)
  if (tasks.length > 0) { //说明没查到数据，说明用户没有收藏过题目
    res = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data)
      }
    })
    console.log(res)
    let subject = new Array()
    let title = res.data
    for (let i = 0; i < title.length; i++) {
      subject.push(title[i].title)
    }
    console.log(subject)
    return subject
  }
  return tasks
}